package com.sunwhite.kaikeba.controller;

import com.sunwhite.kaikeba.entity.User;
import com.sunwhite.kaikeba.utils.ResponseResult;
import com.sunwhite.kaikeba.utils.WeixinHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/user")
public class UserController {
    private final static Logger logger= LoggerFactory.getLogger(UserController.class);

    @Autowired
    private HttpServletRequest request;

    private Map<String,Object> userList=new ConcurrentHashMap<>();
    private Map<String,User> userInfoList=new ConcurrentHashMap<>();

    @RequestMapping("/on_login")
    public ResponseResult login(@RequestParam Map<String,String> param){
        logger.info("接收到参数为：{}",param);
        Map<String, Object> result = WeixinHttpUtil.getAccessToken(param.get("code"));
       if (!StringUtils.isEmpty(result)){
            String openId=result.get("openid").toString();
           Map<String,Object> userInfo = new HashMap<>();
           userInfo.put("openId",openId);
           userList.put("openId",userInfo);
           request.getSession().setAttribute("userInfo",userInfo);
           logger.info("当前登录用户{},系统用户为：{}",userInfo,userList);
           return ResponseResult.oK(userInfo);
       }
        return ResponseResult.build("登录失败！");
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResponseResult addUser(@RequestBody User user){
        Map<String,Object> userInfo = ( Map<String,Object>)request.getSession().getAttribute("userInfo");
        logger.info("用户：{}，获取session信息：{}",user,userInfo);
        user.setOpenId(userInfo.get("openId").toString());
        userInfoList.put(userInfo.get("openId").toString(),user);
        return ResponseResult.oK("添加用户成功！");
    }

    @RequestMapping(value = "/get_info",method = RequestMethod.GET)
    public ResponseResult getUserInfo(){
        Map<String,Object> userInfo = ( Map<String,Object>)request.getSession().getAttribute("userInfo");
        logger.info("当前用户session信息为：{}",userInfo);
        return ResponseResult.oK(userInfoList.get(userInfo.get("openId").toString()));
    }
}
